Skip to content

Bun.gc(true): scavenge libpas + force mimalloc purge so RSS actually drops - #30590

Closed
robobun wants to merge 4 commits into
mainfrom
farm/b5e12f09/gc-scavenge-libpas-mimalloc
Closed

robobun wants to merge 4 commits into
mainfrom
farm/b5e12f09/gc-scavenge-libpas-mimalloc

Conversation

@robobun

@robobun robobun commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Bun.gc(true) (and global.gc() via --expose-gc) ran a full sync JS GC but never told the native allocators to return their freed pages to the OS. After GC:

  • ArrayBuffer backing stores and WTF::StringImpl bodies sat in libpas page caches waiting for the background pas_scavenger thread
  • Bun-owned bytes (Blob stores, external string payloads, bun.default_allocator) sat on mimalloc per-thread heaps waiting for the segment-purge delay

So process.memoryUsage().rss stayed at peak even though the JS heap was empty. Under sustained allocation churn (SSR, long-running daemons, child processes sending IPC) the scavenger/purge never catches up, and RSS ratchets toward OOM while heapUsed looks flat. This is the mechanism behind #21560, #27514, and the detailed repro at https://github.com/jeremiahrhall/repro-bun-rss.

Reproduction

const ring = new Array(8);
for (let r = 1; r <= 200; r++) {
  ring[r % 8] = {
    ta: new Uint8Array(2_000_000),
    s: Buffer.alloc(2_000_000, r & 0x7f).toString('latin1'),
  };
}
ring.fill(undefined);
Bun.gc(true);
// Before: rss ≈ peak (~230MB).  After: rss ≈ start (~40MB).
post-Bun.gc(true) RSS released
before 0% (RSS stays at ~230 MB)
after ~95% (RSS drops to ~40 MB)

Fix

After runGC(true) in VirtualMachine.garbageCollect:

  1. WTF::releaseFastMallocFreeMemory() → bmalloc::api::scavenge() → pas_scavenger_run_synchronously_now() — decommits libpas/Gigacage free pages
  2. mi_collect(true) — forces mimalloc to madvise(MADV_DONTNEED) its free segments

Both are on an already-@branchHint(.cold) path that the user invokes explicitly, so no hot-path cost.

This supersedes #28743 (which only addressed the mimalloc half).

Verification

test/js/bun/util/bun-gc-releases-rss.test.ts runs the churn workload in a subprocess and asserts >50% of peak RSS growth is released by Bun.gc(true). Linux-gated because only MADV_DONTNEED drops pages from RSS immediately; macOS/Windows use lazy reclaim so the runtime fix applies but the RSS measurement doesn't.

  • Without fix: releasedPct: 0.0 → fail
  • With fix (debug+ASAN): releasedPct: 95.3 → pass

Scope

Note this makes explicit Bun.gc(true) / global.gc() reclaim RSS. It does not change the async GC path or add any automatic periodic scavenge — workloads that never call sync GC still rely on the background scavenger, so the SSR-under-continuous-load reports (#14389, #16339) are likely helped but not guaranteed closed by this alone.

Fixes #21560
Fixes #27514
Fixes #20487
Fixes #15020
Fixes #28741

…drops

garbageCollect(sync=true) ran a full JS GC then returned. JS finalizers
freed ArrayBuffer backing stores and WTF::StringImpl bodies into libpas
page caches, and Bun-owned bytes into mimalloc thread heaps, but neither
allocator was told to decommit. RSS stayed at peak (hundreds of MB of
'overhead' above the now-empty JS heap) until libpas's background
scavenger / mimalloc's purge timer eventually ran — and under sustained
allocation churn they never catch up, so RSS ratchets toward OOM while
heapUsed stays flat.

After runGC(true), now call WTF::releaseFastMallocFreeMemory()
(bmalloc::api::scavenge -> pas_scavenger_run_synchronously_now) followed
by mi_collect(true) so both allocators madvise freed pages back to the OS.

On the churn repro from #21560, post-GC RSS released goes from 0% to ~95%.

Fixes #21560
Fixes #27514
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR updates Bun.gc(true) to perform synchronous allocator page scavenging and mimalloc cleanup after the JSC synchronous GC, and adds a Linux-only test that verifies RSS pages are returned to the OS.

Changes

Garbage Collection Memory Scavenging

Layer / File(s) Summary
WTF allocator-release binding
src/jsc/WTF.zig, src/jsc/bindings/wtf-bindings.cpp
Adds WTF__releaseFastMallocFreeMemory() C export and WTF.releaseFastMallocFreeMemory() Zig wrapper that marks the binding and invokes the extern to synchronously scavenge fast-malloc free pages.
Synchronous GC with allocator release
src/jsc/VirtualMachine.zig
Modifies garbageCollect(sync: bool) so the sync path runs the JSC GC, calls jsc.wtf.releaseFastMallocFreeMemory(), then Global.mimalloc_cleanup(true), and returns the GC-reported size.
Process-level RSS release test
test/js/bun/util/bun-gc-releases-rss.test.ts
Adds a Linux-only child process test that performs allocation churn, measures peak and post-GC RSS, asserts a majority of RSS growth is released by Bun.gc(true), and verifies clean exit and empty stderr.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: making Bun.gc(true) trigger scavenging of libpas and forcing mimalloc purge to reduce RSS.
Description check ✅ Passed The description is comprehensive and follows the template with detailed Problem, Reproduction, Fix, Verification, and Scope sections covering all required aspects.
Linked Issues check ✅ Passed Code changes directly address all 5 linked issues (#21560, #27514, #20487, #15020, #28741) by implementing synchronous libpas/mimalloc scavenging after explicit GC to release RSS.
Out of Scope Changes check ✅ Passed All changes are focused on the explicit sync GC path: VirtualMachine.garbageCollect calls new WTF.releaseFastMallocFreeMemory() binding and mimalloc cleanup, plus a targeted Linux regression test.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@robobun

robobun commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:47 PM PT - May 12th, 2026

❌ @robobun, your commit 73c9d5c has 3 failures in Build #53901 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 30590

That installs a local version of the PR into your bun-30590 executable, so you can run:

bun-30590 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 5 issues this PR may fix:

  1. Memory leak when downloading file (both @google-cloud/storage and Bun's S3) #20487 - RSS keeps increasing after file downloads and never drops after Bun.gc(true) despite heapUsed dropping — matches native allocator cache retention pattern
  2. Memory is not getting freed after reading multiple files (Node:fs and Bun.File) #15020 - RSS stays high after reading multiple files even after Bun.gc(true), heapUsed drops but RSS does not — native pages not returned to OS
  3. Memory leak on Nuxt SSR #14389 - Nuxt SSR memory grows over 24h under allocation churn — the exact SSR pattern described in this PR
  4. Memory leak since miggration from node 20 to bun 1.1.43 of a nextjs website #16339 - Next.js SSR memory keeps growing per request, works fine on Node — native allocator pages not returned after GC
  5. Severe GC performance regression with basedpyright language server #26784 - Heap stays flat but overall memory grows over millions of HTTP requests, heap dumps show no JS leak — native allocator cache retention

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #20487
Fixes #15020
Fixes #14389
Fixes #16339
Fixes #26784

🤖 Generated with Claude Code

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. Run mimalloc cleanup after sync GC so freed pages return to the OS #28743 - Also adds mimalloc cleanup after sync GC in VirtualMachine.zig to return freed pages to the OS; PR Bun.gc(true): scavenge libpas + force mimalloc purge so RSS actually drops #30590 supersedes it by additionally scavenging libpas/Gigacage

🤖 Generated with Claude Code

Comment thread src/jsc/VirtualMachine.zig Resolved
@robobun

robobun commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status — ready for maintainer review

All review threads resolved. Gate verified locally: releasedPct: 0.0 on system bun → fail, releasedPct: 92-95 on patched build → pass.

CI

Build Linux (all) macOS (all) Windows
53877 ✅ ✅ ❌ 3 shards
53901 ✅ (pending/pass) ✅ ❌ 1 shard

The new test is Linux-gated (skipIf(!isLinux)) and passes on every Linux shard (debian x64/aarch64, alpine x64/aarch64, x64-asan, x64-baseline). The runtime change (garbageCollect) is only reached on explicit Bun.gc(true) calls.

The Windows failures across both runs are pre-existing flakes unrelated to this diff:

Test Failure Runs
test/js/bun/test/parallel/test-http-should-emit-close-when-connection-is-aborted.ts timeout (4× retry) 53877, 53901
test/js/node/dns/node-dns.test.js google.com resolved to two different IPs between consecutive dns.lookup calls 53877
test/cli/install/bun-install-registry.test.ts peer-dep hoisting picked 1.0.9 instead of 1.0.10 53877

None touch GC, mimalloc, libpas, or the new test file. This diff is green; needs a maintainer to merge past the Windows flake.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/util/bun-gc-releases-rss.test.ts`:
- Around line 50-53: The test currently computes pct = growth > 0 ? (released /
growth) * 100 : 100 which masks cases where growth === 0; change the logic in
the test around the variables peak, start, final, growth and pct to explicitly
assert/fail when growth is 0 before computing pct (e.g., throw or use an
assertion that growth > 0), then compute pct = (released / growth) * 100 and
continue the existing reclamation check so the test cannot pass as a false
positive when RSS growth is zero.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8e8103ea-e543-4823-bac5-bb77493f2dc5

📥 Commits

Reviewing files that changed from the base of the PR and between 0d9b296 and 3107993.

📒 Files selected for processing (4)
  • src/jsc/VirtualMachine.zig
  • src/jsc/WTF.zig
  • src/jsc/bindings/wtf-bindings.cpp
  • test/js/bun/util/bun-gc-releases-rss.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/js/bun/util/bun-gc-releases-rss.test.ts`:
- Around line 53-59: The test currently logs rounded display strings (using
toFixed) for start/peak/final/growth/pct and then later asserts on those rounded
values, causing flaky boundary failures; change the assertions to use the
original numeric variables start, peak, final, growth and pct (not the toFixed
strings) in the expectation checks (the console.log with toFixed should remain
only for human-readable output) — update any assertions that reference the JSON
output or Number(...) of the rounded fields (used around the assertions near the
expect calls referencing growth and releasedPct) to compare against the raw
numeric variables growth and pct instead.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 880e563c-31ae-4b29-8e88-f4314260e562

📥 Commits

Reviewing files that changed from the base of the PR and between 3107993 and 73c9d5c.

📒 Files selected for processing (1)
  • test/js/bun/util/bun-gc-releases-rss.test.ts

@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: this PR predates the Rust rewrite and modifies source files that no longer exist on main (Zig sources removed, src/bun.js/ reorganized into src/jsc/). It cannot merge as-is.

If the underlying issue is still present, it will need a fresh fix against the current tree.

@robobun robobun closed this Jun 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

1 participant